package com.max.rabbitmq.learn.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @description 获取连接工具
 * @author yandong
 * @create 2021年4月07日 08:37:26
 */
public class ConnectionUtil {
    private static volatile ConnectionFactory factory;

    public static Connection getConnection() {
        if (factory == null) {
            synchronized (ConnectionUtil.class) {
                if (factory == null) {
                    factory = new ConnectionFactory();
                    //用户名
                    factory.setUsername("guest");
                    //密码
                    factory.setPassword("guest");
                    //虚拟主机路径
                    factory.setVirtualHost("/maxhost");
                    //broker地址
                    factory.setHost("127.0.0.1");
                    //broker端口 可以通过rabbitmqctl status 命令查看，protocol为amqp的那个
                    factory.setPort(5672);
                }
            }
        }
        Connection connection = null;
        try {
            connection = factory.newConnection();
        } catch (IOException e) {
            System.out.println("获取连接失败，原因：" + e.getMessage());
        } catch (TimeoutException e) {
            System.out.println("获取连接失败，原因：" + e.getMessage());
        }
        return connection;
    }
}
